package cn.com.connext.scrm.service;

import cn.com.connext.scrm.config.Constants;
import cn.com.connext.scrm.domain.master.MerchantNotifyDetails;
import cn.com.connext.scrm.domain.master.MerchantRoll;
import cn.com.connext.scrm.domain.master.MerchantRollDetail;
import cn.com.connext.scrm.repository.master.MerchantRollDetailsRepository;
import cn.com.connext.scrm.repository.master.MerchantRollNotifyRepository;
import cn.com.connext.scrm.repository.master.MerchantRollRepository;
import cn.com.connext.scrm.service.dto.JsonResult;
import cn.com.connext.scrm.service.mapper.MerchantRollDetailsMapper;
import cn.com.connext.scrm.service.mapper.MerchantRollMapper;
import cn.com.connext.scrm.utils.DateUtils;
import cn.com.connext.scrm.utils.wechat.WeiXinUtils;
import cn.com.connext.scrm.web.rest.req.WxBusinessVolumeReq;
import cn.com.connext.scrm.web.rest.req.WxMerchanRollQueryPage;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import javax.persistence.criteria.Predicate;
import java.text.SimpleDateFormat;
import java.time.ZonedDateTime;
import java.util.*;

/**
 * @Description:
 * @author: ZHaoYul
 * @date: 2021/9/13 14:35
 */
@Service
public class WxMerchantRollServiceImpl implements WxMerchantRollService {

    private static final Logger logger = LoggerFactory.getLogger(WxMerchantRollServiceImpl.class);
    @Autowired
    private MerchantRollMapper merchantRollMapper;

    @Autowired
    private MerchantRollDetailsMapper merchantRollDetailMapper;

    @Autowired
    private MerchantRollDetailsRepository merchantRollDetailsRepository;

    @Autowired
    private MerchantRollNotifyRepository merchantRollNotifyRepository;

    @Autowired
    private MerchantRollRepository merchantRollRepository;

    @Autowired
    private WeiXinUtils weiXinUtils;


    @Override
    public MerchantNotifyDetails getNotifyObjByCode(String code) {
        return merchantRollNotifyRepository.getNotifyObjByCode(code);
    }

    /**
     * 根据id 更新 notify表信息
     * @param merchantNotifyDetails1
     * @return
     */
    @Override
    public MerchantNotifyDetails updateNotifyById(MerchantNotifyDetails merchantNotifyDetails1) {
        return merchantRollNotifyRepository.saveAndFlush(merchantNotifyDetails1);
    }
    @Override
    public void saveOrUpdate(JSONObject jsonObject) {
        logger.info("packMerchantData ",jsonObject.toJSONString());
        //验证数据 是否为正常数据格式
        if (StringUtils.isBlank(jsonObject.getString("belong_merchant"))) {
            return;
        }
        Date originalavailable_start_time = jsonObject.getDate("available_begin_time");
        jsonObject.remove("available_begin_time");

        Date originalexpire_time = jsonObject.getDate("available_end_time");
        jsonObject.remove("available_end_time");
        MerchantRoll merchantRoll = JSONObject.toJavaObject(jsonObject, MerchantRoll.class);
//        merchantRoll.setAvailable_begin_time(originalavailable_start_time);
//        MerchantRoll merchantRoll = JSONObject.parseObject(jsonObject.toJSONString(), MerchantRoll.class);

        ZonedDateTime beginTime = ZonedDateTime.now();
        ZonedDateTime endTime = ZonedDateTime.now();
        //开始日期转换
        if (null != originalavailable_start_time) {
            beginTime = DateUtils.toZonedDateTime(originalavailable_start_time);
            merchantRoll.setAvailable_begin_time(beginTime);
        }
        //结束日期转换
        if (null != originalexpire_time) {
            endTime = DateUtils.toZonedDateTime(originalexpire_time);
            merchantRoll.setAvailable_end_time(endTime);
        }
        //send 发卷请求单号
        if (StringUtils.isNotBlank(jsonObject.getString("send_request_no"))) {
            merchantRoll.setOut_request_no(jsonObject.getString("send_request_no"));
        }
        //coupon_code openid unionId
        String coupon_code = jsonObject.getString("coupon_code");
        String openid = jsonObject.getString("openid");
        String unionId = jsonObject.getString("unionId");

        String mainId = "";
        if (StringUtils.isNotBlank(jsonObject.getString("id"))) {
//            MerchantRoll getMerchant =  merchantRollRepository.getMerchantRollByOne(coupon_code,openid,unionId);
            MerchantRoll getMerchant =  merchantRollRepository.getOne(jsonObject.getString("id"));
            mainId = getMerchant.getId();
            merchantRoll.setId(getMerchant.getId());
            merchantRoll.setUpdate_time(new Date());
            merchantRoll.setCreateTime(getMerchant.getCreateTime());
        } else {
            mainId = UUID.randomUUID().toString();
            merchantRoll.setId(mainId);
            Date date = new Date();
            merchantRoll.setVolumeStart("0");
            merchantRoll.setCreateTime(date);
            merchantRoll.setUpdate_time(date);
//            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
//            merchantRoll.setOut_request_no(merchantRoll.getBelong_merchant()+sdf.format(date)+mainId);
        }
//        if (StringUtils.isNotBlank(coupon_code)
//            &&StringUtils.isNotBlank(openid)
//            &&StringUtils.isNotBlank(unionId)) {
//
//        }
        logger.info("商家卷主表入库数据：{} ", JSON.toJSONString(merchantRoll));
        //更新或新增 微信商家卷
        merchantRollRepository.saveAndFlush(merchantRoll);

//        JSONObject detailsData = this.packDataJSONObject(jsonObject);

        MerchantRollDetail merchantRollDetail = JSONObject.toJavaObject(jsonObject, MerchantRollDetail.class);
        merchantRollDetail.setMainId(mainId);

        if (StringUtils.isNotBlank(mainId)) {

            MerchantRollDetail getMerchantDetails =  merchantRollDetailsRepository.getOneMerchantDetails(mainId);
//            merchantRollDetail.setOpenid(openid);
//            merchantRollDetail.setUnionId(unionId);
//            merchantRollDetail.setCoupon_code(coupon_code);

            if (null != getMerchantDetails) {
                merchantRollDetail.setId(getMerchantDetails.getId());
                merchantRollDetail.setUpdate_time(new Date());
            } else {
                merchantRollDetail.setId(UUID.randomUUID().toString());
                merchantRollDetail.setCreate_time(new Date());
                merchantRollDetail.setUpdate_time(new Date());
                merchantRollDetail.setNotify_appid(Constants.APPID);
            }

        }
        logger.info("商家卷详细表入库数据：{} ", JSON.toJSONString(merchantRollDetail));
        //更新或新增微信商家卷详细表

        merchantRollDetailsRepository.saveAndFlush(merchantRollDetail);

    }

    @Override
    public void packMerchantData(JSONObject jsonObject) {
        logger.info("packMerchantData ",jsonObject.toJSONString());
        //验证数据 是否为正常数据格式
        if (StringUtils.isBlank(jsonObject.getString("belong_merchant"))) {
            return;
        }
        MerchantRoll merchantRoll = JSONObject.toJavaObject(jsonObject, MerchantRoll.class);
//        MerchantRoll merchantRoll = JSONObject.parseObject(jsonObject.toJSONString(), MerchantRoll.class);

        ZonedDateTime beginTime = ZonedDateTime.now();
        ZonedDateTime endTime = ZonedDateTime.now();
        //开始日期转换
        if (null != jsonObject.getDate("available_start_time")) {
            beginTime = DateUtils.toZonedDateTime(jsonObject.getDate("available_start_time"));
            merchantRoll.setAvailable_begin_time(beginTime);
        }
        //结束日期转换
        if (null != jsonObject.getDate("expire_time")) {
            endTime = DateUtils.toZonedDateTime(jsonObject.getDate("expire_time"));
            merchantRoll.setAvailable_end_time(endTime);
        }
        //send 发卷请求单号
        if (StringUtils.isNotBlank(jsonObject.getString("send_request_no"))) {
            merchantRoll.setOut_request_no(jsonObject.getString("send_request_no"));
        }
        //coupon_code openid unionId
        String coupon_code = jsonObject.getString("coupon_code");
        String openid = jsonObject.getString("openid");
        String unionId = jsonObject.getString("unionId");

        String mainId = "";
        if (StringUtils.isNotBlank(coupon_code)
            &&StringUtils.isNotBlank(openid)
            &&StringUtils.isNotBlank(unionId)) {
            MerchantRoll getMerchant =  merchantRollRepository.getMerchantRollByOne(coupon_code,openid,unionId);

            if (null != getMerchant) {
                mainId = getMerchant.getId();
                merchantRoll.setId(getMerchant.getId());
                merchantRoll.setUpdate_time(new Date());
            } else {
                mainId = UUID.randomUUID().toString();
                merchantRoll.setId(mainId);
                merchantRoll.setCreateTime(new Date());
            }
        }
        logger.info("商家卷主表入库数据：{} ", JSON.toJSONString(merchantRoll));
        //更新或新增 微信商家卷
        merchantRollRepository.saveAndFlush(merchantRoll);

        JSONObject detailsData = this.packDataJSONObject(jsonObject);

        MerchantRollDetail merchantRollDetail = JSONObject.parseObject(detailsData.toJSONString(), MerchantRollDetail.class);
        merchantRollDetail.setMainId(mainId);
        if (StringUtils.isNotBlank(coupon_code)
            &&StringUtils.isNotBlank(openid)
            &&StringUtils.isNotBlank(unionId)) {

            MerchantRollDetail getMerchantDetails =  merchantRollDetailsRepository.getMerchantRollDetailsByOne(coupon_code,openid,unionId);
            merchantRollDetail.setOpenid(openid);
            merchantRollDetail.setUnionId(unionId);
            merchantRollDetail.setCoupon_code(coupon_code);

            if (null != getMerchantDetails) {
                merchantRollDetail.setId(getMerchantDetails.getId());
                merchantRollDetail.setUpdate_time(new Date());
            } else {
                merchantRollDetail.setCreate_time(new Date());
            }

        }
        logger.info("商家卷详细表入库数据：{} ", JSON.toJSONString(merchantRollDetail));
        //更新或新增微信商家卷详细表

        merchantRollDetailsRepository.saveAndFlush(merchantRollDetail);

    }

    public JSONObject packDataJSONObject(JSONObject jsonObject){
        JSONObject objectData = new JSONObject();
        //样式信息
        JSONObject display_pattern_info = jsonObject.getJSONObject("display_pattern_info");
        //核销规则
        JSONObject coupon_use_rule = jsonObject.getJSONObject("coupon_use_rule");
        //自定义入口
        JSONObject custom_entrance = jsonObject.getJSONObject("custom_entrance");

        //样式信息组装
        if (null!= display_pattern_info) {
            objectData.putAll(display_pattern_info);
        }
        //卷核销规则组装
        if (null!= coupon_use_rule) {
            objectData.putAll(coupon_use_rule);
            //券可核销时间
            JSONObject coupon_available_time = coupon_use_rule.getJSONObject("coupon_available_time");
            //固定面额满减券使用规则
            JSONObject fixed_normal_coupon = coupon_use_rule.getJSONObject("fixed_normal_coupon");
            //折扣券使用规则
            JSONObject discount_coupon = coupon_use_rule.getJSONObject("discount_coupon");
            //换购券使用规则
            JSONObject exchange_coupon = coupon_use_rule.getJSONObject("exchange_coupon");

            if (null != coupon_available_time) {
                objectData.putAll(coupon_available_time);
            }
            if (null != fixed_normal_coupon) {
                //stock_type为NORMAL时必填。
                objectData.putAll(fixed_normal_coupon);
            }
            if (null != discount_coupon) {
                //stock_type为DISCOUNT时必填。
                objectData.putAll(discount_coupon);

            }
            if (null != exchange_coupon) {
                //stock_type为EXCHANGE时必填。
                objectData.putAll(exchange_coupon);

            }
        }
        // 自定义入口	 卡详情页面，可选择多种入口引导用户
        if (null != custom_entrance) {
            objectData.putAll(custom_entrance);
            //自定义入口 -》 小程序入口
            JSONObject mini_programs_info = custom_entrance.getJSONObject("mini_programs_info");
            if (null != mini_programs_info) {
                //需要小程序APPID、path、入口文案、引导文案。如果需要跳转小程序，APPID、path、入口文案为必填，引导文案非必填。
                //appid要与归属商户号有M-A or M-m-suba关系。
                objectData.putAll(mini_programs_info);
            }
        }
        return objectData;
    }

    /**
     * 启用商家卷
     * @param req
     * @return
     */
    @Override
    public JsonResult startWxBusinessVolume(WxBusinessVolumeReq req) {
        logger.info("启用微信商家卷入参req:{} ",JSON.toJSONString(req));
        JsonResult jsonResult = new JsonResult();
        String mainId = req.getMainId();
        MerchantRoll main = merchantRollRepository.findOne(mainId);
        logger.info("查询商家卷主表返回参数main：{}",JSON.toJSONString(main));

        if (null == main) {
            jsonResult.setState(JsonResult.ERROR);
            jsonResult.setMessage("无效的mainId");
            return jsonResult;
        }
        //更改启用状态
//        if (StringUtils.isNotBlank(main.getVolumeStart())&&"0".equals(main.getVolumeStart())) {
//            main.setVolumeStart("1");
//            merchantRollRepository.saveAndFlush(main);
//        }
        MerchantRollDetail detail = merchantRollDetailsRepository.getOneMerchantDetails(mainId);

        logger.info("查询商家卷详细表返回参数detail：{}",JSON.toJSONString(detail));
        if (null == detail) {
            jsonResult.setState(JsonResult.ERROR);
            jsonResult.setMessage("无效的details数据");
            return jsonResult;
        }
        //卷详情
        if (StringUtils.isBlank(detail.getWxCoupon_image_url())&&StringUtils.isNotBlank(detail.getCoupon_image_url())) {
            String detailsUrl = weiXinUtils.uploadHttp(detail.getCoupon_image_url());
            JSONObject object = JSONObject.parseObject(detailsUrl);
            if (StringUtils.isNotBlank(object.getString("media_url"))) {
                String media_url = object.getString("media_url");
                detail.setWxCoupon_image_url(media_url);
                merchantRollDetailsRepository.saveAndFlush(detail);
            }
        }
        //logo img
        if (StringUtils.isBlank(detail.getWxMerchant_logo_url())&&StringUtils.isNotBlank(detail.getMerchant_logo_url())) {
            String detailsUrl = weiXinUtils.uploadHttp(detail.getMerchant_logo_url());
            JSONObject object = JSONObject.parseObject(detailsUrl);
            if (StringUtils.isNotBlank(object.getString("media_url"))) {
                String media_url = object.getString("media_url");
                detail.setWxMerchant_logo_url(media_url);
                merchantRollDetailsRepository.saveAndFlush(detail);
            }
        }
        ObjectMapper objectMapper = new ObjectMapper();
        ObjectNode rootNode = objectMapper.createObjectNode();
        //组装请求参数
        this.packCerWxBusinessVolume(main,detail,rootNode);
        String wxHttpClient = weiXinUtils.postWxHttpClient("https://api.mch.weixin.qq.com/v3/marketing/busifavor/stocks", objectMapper, rootNode);
        logger.info("调用微信接口返回参数wxHttpClient：{}",wxHttpClient);
        if (StringUtils.isNotBlank(wxHttpClient)) {
            JSONObject jsonObject = JSONObject.parseObject(wxHttpClient);
            if (null == jsonObject.getInteger("stock_id")) {
                if (StringUtils.isNotBlank(jsonObject.getString("message"))) {
                    jsonResult.setState(JsonResult.ERROR);
                    jsonResult.setMessage(jsonObject.getString("message"));
                    return jsonResult;
                } else {
                    jsonResult.setState(JsonResult.ERROR);
                    jsonResult.setMessage("启用失败");
                }

            } else {
                jsonResult.setState(JsonResult.SUCCESS);
                jsonResult.setData(jsonObject);
                main.setStock_id(jsonObject.getString("stock_id"));
                main.setWx_create_time(jsonObject.getDate("create_time"));
                main.setVolumeStart("1");
                SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
                main.setOut_request_no(main.getBelong_merchant()+sdf.format(new Date())+mainId);
                //调用并更新
                merchantRollRepository.saveAndFlush(main);

            }
        } else {
            jsonResult.setState(JsonResult.ERROR);
            jsonResult.setMessage("启用失败");
        }

        return jsonResult;
    }

//    public static void main(String[] args) throws IOException {
//        String mainStr = "{\"available_begin_time\":\"2021-10-01T00:00+08:00[Asia/Shanghai]\",\"available_day_after_receive\":\"5\",\"available_end_time\":\"2021-10-31T00:00+08:00[Asia/Shanghai]\",\"belong_merchant\":\"123456789\",\"comment\":\"适用商品范围\",\"coupon_code_mode\":\"WECHATPAY_MODE\",\"createTime\":1635501900000,\"goods_name\":\"适用商品范围\",\"id\":\"eeb4d58a-49a4-4e69-b0f4-0d6a967900a9\",\"shareable\":\"false\",\"stock_name\":\"批次名称\",\"stock_type\":\"DISCOUNT\",\"transferable\":\"false\"}";
//        String datailsStr = "{\"appid\":\"467454651354\",\"background_color\":\"#FF7A7A\",\"code_display_mode\":\"BARCODE\",\"create_time\":1635501906000,\"entrance_words\":\"欢迎选购\",\"guiding_words\":\"获取更多优惠\",\"hall_id\":\"6666666\",\"id\":\"9bd23c78-8bb0-4e08-8b9a-548a3471d263\",\"mainId\":\"eeb4d58a-49a4-4e69-b0f4-0d6a967900a9\",\"max_coupons\":100,\"max_coupons_by_day\":50,\"max_coupons_per_user\":1,\"merchant_name\":\"商户名称\",\"mini_programs_appid\":\"wx234545656765876\",\"mini_programs_path\":\"/path/index/index\",\"natural_person_limit\":false,\"prevent_api_abuse\":false,\"shareable\":false,\"store_id\":\"123\",\"transferable\":false}";
//        MerchantRoll main = JSONObject.parseObject(mainStr,MerchantRoll.class);
//        MerchantRollDetail detail = JSONObject.parseObject(datailsStr,MerchantRollDetail.class);
//
//        ObjectMapper objectMapper = new ObjectMapper();
//        ObjectNode rootNode = objectMapper.createObjectNode();
////        ObjectNode rootNode = (ObjectNode)objectMapper.readTree(str);
//        rootNode.put("stock_name",main.getStock_name());
//        rootNode.put("belong_merchant",main.getBelong_merchant());
//        rootNode.put("comment",main.getComment());
//        rootNode.put("goods_name",main.getGoods_name());
//        rootNode.put("stock_type","NORMAL");
//        rootNode.put("out_request_no",main.getOut_request_no());
//        rootNode.put("coupon_code_mode",main.getCoupon_code_mode());
//        rootNode.put("subsidy",main.getSubsidy());
//
////        JSONObject object = this.packCouponUseRule(main, detail);
//        System.out.println(packCouponUseRule(main,detail).toString());
//        //核销规则
//        rootNode.putPOJO("coupon_use_rule",packCouponUseRule(main,detail));
//
//        //发放规则
//        rootNode.putPOJO("stock_send_rule",new JSONObject(){{
//            put("max_coupons",detail.getMax_coupons());
//            put("max_coupons_per_user",detail.getMax_coupons_per_user());
//            put("max_coupons_by_day",detail.getMax_coupons_by_day());
//            put("natural_person_limit",detail.isNatural_person_limit());
//            put("prevent_api_abuse",detail.isPrevent_api_abuse());
//            put("transferable",detail.isTransferable());
//            put("shareable",detail.isShareable());
//        }});
//        //自定义入口
//        rootNode.putPOJO("custom_entrance",new JSONObject(){{
//            put("mini_programs_info",new JSONObject(){{
//                put("mini_programs_appid",detail.getMini_programs_appid());
//                put("mini_programs_path",detail.getMini_programs_path());
//                put("entrance_words",detail.getEntrance_words());
//                put("guiding_words",detail.getGuiding_words());
//            }});
//            put("appid",detail.getAppid());
//            put("hall_id",detail.getHall_id());
//            put("store_id",detail.getStore_id());
//            put("code_display_mode",detail.getCode_display_mode());
//        }});
//        //样式信息
//        rootNode.putPOJO("display_pattern_info",new JSONObject(){{
//            put("description",detail.getDescription());
//            put("merchant_logo_url",detail.getMerchant_logo_url());
//            put("merchant_name",detail.getMerchant_name());
//            put("background_color",detail.getBackground_color());
//            put("coupon_image_url",detail.getCoupon_image_url());
//        }});
//        //事件通知配置
//        rootNode.putPOJO("notify_config",new JSONObject(){{
//            put("notify_appid",detail.getNotify_appid());
//        }});
//
////
////        String str = "{\n" +
////            "    \"stock_name\": \"批次名称\",\n" +
////            "    \"belong_merchant\": \"123456\",\n" +
////            "    \"comment\": \"适用商品范围\",\n" +
////            "    \"goods_name\": \"适用商品范围\",\n" +
////            "    \"stock_type\": \"DISCOUNT\",\n" +
////            "    \"out_request_no\": null,\n" +
////            "    \"coupon_code_mode\": \"WECHATPAY_MODE\",\n" +
////            "    \"subsidy\": null,\n" +
////            "    \"coupon_use_rule\": \"{\\\"coupon_available_time\\\":{\\\"available_day_after_receive\\\":\\\"5\\\",\\\"available_end_time\\\":\\\"2021-10-31T00:00:00Z\\\",\\\"available_begin_time\\\":\\\"2021-10-01T00:00:00Z\\\"},\\\"fixed_normal_coupon\\\":{\\\"discount_amount\\\":\\\"1\\\",\\\"transaction_minimum\\\":\\\"1\\\"}}\",\n" +
////            "    \"stock_send_rule\": \"{\\\"shareable\\\":false,\\\"prevent_api_abuse\\\":false,\\\"max_coupons_by_day\\\":50,\\\"natural_person_limit\\\":false,\\\"transferable\\\":false,\\\"max_coupons_per_user\\\":1,\\\"max_coupons\\\":100}\",\n" +
////            "    \"custom_entrance\": \"{\\\"store_id\\\":\\\"123\\\",\\\"hall_id\\\":\\\"6666666\\\",\\\"mini_programs_info\\\":{\\\"guiding_words\\\":\\\"获取更多优惠\\\",\\\"mini_programs_appid\\\":\\\"wx234545656765876\\\",\\\"entrance_words\\\":\\\"欢迎选购\\\",\\\"mini_programs_path\\\":\\\"/path/index/index\\\"},\\\"appid\\\":\\\"467454651354\\\",\\\"code_display_mode\\\":\\\"BARCODE\\\"}\",\n" +
////            "    \"display_pattern_info\": \"{\\\"background_color\\\":\\\"#FF7A7A\\\",\\\"merchant_name\\\":\\\"商户名称\\\"}\",\n" +
////            "    \"notify_config\": \"{}\"\n" +
////            "}\n" +
////            "]";
//
////        ObjectNode rootNode = objectMapper.createObjectNode();
//
////        rootNode.putAll();
//        String url = "https://api.mch.weixin.qq.com/v3/marketing/busifavor/stocks";
//
//        //序列号
//        String merchantSerialNumber = "32075FA334FA59896AEF7879670E82AB13075120";
//        //商户号
//        String merchantId = "1612505750";
//        String apiV3Key = "20210805A161000ADiageoOmata0417y";
//        //私钥
//        PrivateKey merchantPrivateKey = null;
//        WechatPayHttpClientBuilder builder = null;
//        String bodyAsString = null;
//        try {
//            merchantPrivateKey = PemUtil.loadPrivateKey(
//                new FileInputStream("D://apiclient_key.pem"));
//            //不需要传入微信支付证书了 需要v3Key
//            AutoUpdateCertificatesVerifier verifier = new AutoUpdateCertificatesVerifier(
//                new WechatPay2Credentials(merchantId, new PrivateKeySigner(merchantSerialNumber, merchantPrivateKey)),
//                apiV3Key.getBytes("utf-8"));
//            builder = WechatPayHttpClientBuilder.create()
//                .withMerchant(merchantId, merchantSerialNumber, merchantPrivateKey)
//                .withValidator(new WechatPay2Validator(verifier));
//            HttpClient httpClient = builder.build();
//            HttpPost httpPost = new HttpPost(url);
//            httpPost.addHeader("Accept", "application/json");
//            httpPost.addHeader("Content-type","application/json; charset=utf-8");
//            ByteArrayOutputStream bos = new ByteArrayOutputStream();
////            ObjectMapper objectMapper = new ObjectMapper();
////            ObjectNode rootNode = objectMapper.createObjectNode();
//            objectMapper.writeValue(bos, rootNode);
//            httpPost.setEntity(new StringEntity(bos.toString("UTF-8"), "UTF-8"));
//            CloseableHttpResponse response = (CloseableHttpResponse) httpClient.execute(httpPost);
//            bodyAsString = EntityUtils.toString(response.getEntity());
//            System.out.println(bodyAsString);
//            System.out.println(bodyAsString);
//            System.out.println(bodyAsString);
//            System.out.println(bodyAsString);
//
//        } catch (FileNotFoundException | UnsupportedEncodingException e) {
//            e.printStackTrace();
//        } catch (ClientProtocolException e) {
//            e.printStackTrace();
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
//
//    }

    @Override
    public JsonResult page(WxMerchanRollQueryPage req) {
        PageImpl<MerchantRoll> pageTasks = cover(req);
        JsonResult jsonResult = new JsonResult();
        jsonResult.setData(pageTasks);
        jsonResult.setState(0);
        return jsonResult;
    }

    @Override
    public JsonResult details(WxBusinessVolumeReq req) {
        JsonResult jsonResult = new JsonResult();
        if (StringUtils.isBlank(req.getMainId())) {
            jsonResult.setState(JsonResult.ERROR);
            jsonResult.setMessage("参数不正确");
            return jsonResult;
        }
        String mainId = req.getMainId();
        MerchantRoll main = merchantRollRepository.findOne(mainId);
        logger.info("查询商家卷主表返回参数main：{}",JSON.toJSONString(main));

        if (null == main) {
            jsonResult.setState(JsonResult.ERROR);
            jsonResult.setMessage("无效的mainId");
            return jsonResult;
        }

        MerchantRollDetail detail = merchantRollDetailsRepository.getOneMerchantDetails(mainId);

        logger.info("查询商家卷详细表返回参数detail：{}",JSON.toJSONString(detail));
        JSONObject object = new JSONObject();
        object.put("main",main);
        object.put("detail",detail);
        if ("1".equals(main.getVolumeStart())) {
            ObjectMapper objectMapper = new ObjectMapper();
            ObjectNode rootNode = objectMapper.createObjectNode();
            String wxHttpClient = weiXinUtils.getWxHttpClient("https://api.mch.weixin.qq.com/v3/marketing/busifavor/stocks/" + main.getStock_id(), objectMapper, rootNode);
            JSONObject object1 = JSONObject.parseObject(wxHttpClient, JSONObject.class);
            if (null != object1.getJSONObject("send_count_information")) {
                JSONObject send_count_information = object1.getJSONObject("send_count_information");
                object.put("count",send_count_information);
            }
        }

        jsonResult.setData(object);
        return jsonResult;
    }

    @Override
    public JsonResult deleteOne(WxBusinessVolumeReq req) {
        JsonResult jsonResult = new JsonResult();
        if (StringUtils.isBlank(req.getMainId())) {
            jsonResult.setState(JsonResult.ERROR);
            jsonResult.setMessage("参数不正确");
            return jsonResult;
        }
        String mainId = req.getMainId();
        MerchantRoll main = merchantRollRepository.findOne(mainId);
        logger.info("查询商家卷主表返回参数main：{}",JSON.toJSONString(main));

        if (null == main ) {
            jsonResult.setState(JsonResult.ERROR);
            jsonResult.setMessage("无效的mainId");
            return jsonResult;
        }
        if ("1".equals(main.getVolumeStart())) {
            jsonResult.setState(JsonResult.ERROR);
            jsonResult.setMessage("商家卷已启用 不可删除");
            return jsonResult;
        }

        MerchantRollDetail detail = merchantRollDetailsRepository.getOneMerchantDetails(mainId);

        logger.info("查询商家卷详细表返回参数detail：{}",JSON.toJSONString(detail));
        if (null != main && null != detail) {
            merchantRollDetailsRepository.delete(detail.getId());
            merchantRollRepository.delete(main.getId());
        }
        return jsonResult;
    }

    @Override
    public JsonResult getNeckRollList(WxMerchanRollQueryPage req) {

        PageImpl<MerchantNotifyDetails> pageTasks = coverNeck(req);
        JsonResult jsonResult = new JsonResult();
        jsonResult.setData(pageTasks);
        jsonResult.setState(0);
        return jsonResult;
    }
    private PageImpl coverNeck(WxMerchanRollQueryPage req) {
        int currentPage = (req.getCurrentPage() - 1) < 0 ? 0 : req.getCurrentPage() - 1;
        int pageSize = req.getPageSize() < 1 ? 10 : req.getPageSize();
        Pageable pageable = new PageRequest(currentPage, pageSize);
        Specification<MerchantNotifyDetails> specification = (root, query, criteriaBuilder) -> {
            List<Predicate> list = new ArrayList<>();
            //产品名字
            if (StringUtils.isNotBlank(req.getStockId())) {
                list.add(criteriaBuilder.equal(root.get("stock_id"),  req.getStockId()));
            }
            return criteriaBuilder.and(list.toArray(new Predicate[0]));
        };
        Page page = merchantRollNotifyRepository.findAll(specification, pageable);
        List<MerchantNotifyDetails> orderList = page.getContent();
        PageImpl<MerchantNotifyDetails> pageTasks = new PageImpl<>(orderList, pageable, page.getTotalElements());
        return pageTasks;
    }

    private PageImpl cover(WxMerchanRollQueryPage req) {
        int currentPage = (req.getCurrentPage() - 1) < 0 ? 0 : req.getCurrentPage() - 1;
        int pageSize = req.getPageSize() < 1 ? 10 : req.getPageSize();
        Pageable pageable = new PageRequest(currentPage, pageSize, new Sort(Sort.Direction.DESC, "createTime"));
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Specification<MerchantRoll> specification = (root, query, criteriaBuilder) -> {
            List<Predicate> list = new ArrayList<>();
            //卷名称
            if (StringUtils.isNotBlank(req.getStockName())) {
                list.add(criteriaBuilder.like(root.get("stock_name"), "%" + req.getStockName() + "%"));
            }
            //产品名字
            if (StringUtils.isNotBlank(req.getStockId())) {
                list.add(criteriaBuilder.equal(root.get("stock_id"),  req.getStockId()));
            }

            try {
                //创建时间
                if (StringUtils.isNotBlank(req.getCreateStart())) {
                    list.add(criteriaBuilder.greaterThanOrEqualTo(root.get("createTime"), sdf.parse(req.getCreateStart())));
                }
                if (StringUtils.isNotBlank(req.getCreateEnd())) {
                    list.add(criteriaBuilder.lessThanOrEqualTo(root.get("createTime"), sdf.parse(req.getCreateEnd())));
                }
                //订单时间
                if (StringUtils.isNotBlank(req.getHxStart())) {
                    list.add(criteriaBuilder.greaterThanOrEqualTo(root.get("available_begin_time"), sdf.parse(req.getHxStart())));
                }
                if (StringUtils.isNotBlank(req.getHxEnd())) {
                    list.add(criteriaBuilder.lessThanOrEqualTo(root.get("available_begin_time"), sdf.parse(req.getHxEnd())));
                }

            }catch (Exception e) {
//                log.error("日期格式化Exception:" + e.getMessage());
            }


            return criteriaBuilder.and(list.toArray(new Predicate[0]));
        };
        Page page = merchantRollRepository.findAll(specification, pageable);
        List<MerchantRoll> orderList = page.getContent();
        PageImpl<MerchantRoll> pageTasks = new PageImpl<>(orderList, pageable, page.getTotalElements());
        return pageTasks;
    }

//    private void fileUpload(){
//        String filePath = "D://微信图片_20180914095848.jpg";
//        try {
//            URI uri = new URI("https://api.mch.weixin.qq.com/v3/marketing/favor/media/image-upload");
//            File file = new File(filePath);
//
//            try (FileInputStream ins1 = new FileInputStream(file)) {
//                String sha256 = DigestUtils.sha256Hex(ins1);
//                try (InputStream ins2 = new FileInputStream(file)) {
//                    HttpPost request = new WechatPayUploadHttpPost.Builder(uri)
//                        .withImage(file.getName(), sha256, ins2)
//                        .build();
//                    CloseableHttpResponse response1 = httpClient.execute(request);
//                    HttpEntity entity = response1.getEntity();
//                    String s = EntityUtils.toString(entity);
//                }
//            }
//        } catch (Exception e) {
//
//        }
//
//    }


    /**
     * 组装商家卷参数
     */
    private void packCerWxBusinessVolume(MerchantRoll main, MerchantRollDetail detail, ObjectNode rootNode){
        rootNode.put("stock_name",main.getStock_name());
        rootNode.put("belong_merchant",main.getBelong_merchant());
        rootNode.put("comment",main.getComment());
        rootNode.put("goods_name",main.getGoods_name());
        rootNode.put("stock_type",main.getStock_type());
        rootNode.put("out_request_no",main.getOut_request_no());
        rootNode.put("coupon_code_mode",main.getCoupon_code_mode());
        if (StringUtils.isNotBlank(main.getSubsidy())) {
            rootNode.put("subsidy",main.getSubsidy());
        }
        //核销规则
        rootNode.putPOJO("coupon_use_rule",this.packCouponUseRule(main,detail));

        //发放规则
        rootNode.putPOJO("stock_send_rule",new JSONObject(){{
            put("max_coupons",detail.getMax_coupons());
            put("max_coupons_per_user",detail.getMax_coupons_per_user());
            put("max_coupons_by_day",detail.getMax_coupons_by_day());
            put("natural_person_limit",detail.isNatural_person_limit());
            put("prevent_api_abuse",detail.isPrevent_api_abuse());
            put("transferable",detail.isTransferable());
            put("shareable",detail.isShareable());
        }});
        //自定义入口
        rootNode.putPOJO("custom_entrance",new JSONObject(){{
            put("mini_programs_info",new JSONObject(){{
                put("mini_programs_appid",detail.getMini_programs_appid());
                put("mini_programs_path",detail.getMini_programs_path());
                put("entrance_words",detail.getEntrance_words());
                put("guiding_words",detail.getGuiding_words());
            }});
            put("appid",detail.getAppid());
            put("hall_id",detail.getHall_id());
            put("store_id",detail.getStore_id());
            if (StringUtils.isNotBlank(detail.getCode_display_mode())) {
                put("code_display_mode",detail.getCode_display_mode());
            }

        }});
        //样式信息
        rootNode.putPOJO("display_pattern_info",new JSONObject(){{
            if (StringUtils.isNotBlank(detail.getDescription())) {
                put("description",detail.getDescription());
            }
            if (StringUtils.isNotBlank(detail.getMerchant_logo_url())) {
                put("merchant_logo_url",detail.getMerchant_logo_url());
            }
            if (StringUtils.isNotBlank(detail.getMerchant_name())) {
                put("merchant_name",detail.getMerchant_name());
            }
            if (StringUtils.isNotBlank(detail.getBackground_color())) {
                put("background_color",detail.getBackground_color());
            }
            if (StringUtils.isNotBlank(detail.getCoupon_image_url())) {
                put("coupon_image_url",detail.getCoupon_image_url());
            }

        }});
        //事件通知配置
        if (StringUtils.isNotBlank(detail.getNotify_appid())) {
            rootNode.putPOJO("notify_config",new JSONObject(){{
                put("notify_appid",detail.getNotify_appid());
            }});
        }
    }
    //组装核销规则
    private JSONObject packCouponUseRule(MerchantRoll main, MerchantRollDetail detail){
        JSONObject object = new JSONObject();
        object.put("use_method",detail.getUse_method());
        object.put("mini_programs_appid",detail.getHx_mini_programs_appid());
        object.put("mini_programs_path",detail.getHx_mini_programs_path());
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
        object.put("coupon_available_time",new JSONObject(){{
            if (null!= main.getAvailable_begin_time()) {
                String format = formatter.format(new Date());
                System.out.println(format);
                System.out.println(format);
                System.out.println(main.getAvailable_begin_time().toInstant().toEpochMilli());
                put("available_begin_time",formatter.format(main.getAvailable_begin_time().toInstant().toEpochMilli()));
            }
            if (null!= main.getAvailable_end_time()) {
                put("available_end_time",formatter.format(main.getAvailable_end_time().toInstant().toEpochMilli()));
            }
            if (StringUtils.isNotBlank(main.getAvailable_day_after_receive())) {
                put("available_day_after_receive",Integer.valueOf(main.getAvailable_day_after_receive()));
            }

            if (StringUtils.isNotBlank(detail.getWeek_day())) {
                put("available_week",new HashMap<String,Object>(){{
                    put("week_day",Arrays.asList(detail.getWeek_day().split(",")));
                    //需要数据支撑 暂时不做 后期补充
//                put("available_day_time",Arrays.asList(detail.getWeek_day().split(",")));
                }});
            }

            //无规律的有效时间段  暂定
//            put("irregulary_avaliable_time",main.getAvailable_day_after_receive());

            if (null!= detail.getWait_days_after_receive()&&detail.getWait_days_after_receive()>0) {
                put("wait_days_after_receive",main.getAvailable_day_after_receive());
            }

        }});
//        固定面额满减券
        if ("NORMAL".equals(main.getStock_type())) {
            object.put("fixed_normal_coupon",new JSONObject(){{
                put("discount_amount",detail.getDiscount_amount());
                put("transaction_minimum",detail.getTransaction_minimum());
            }});
        }
        if ("DISCOUNT".equals(main.getStock_type())) {
            //折扣卷
        object.put("discount_coupon",new JSONObject(){{
            put("discount_percent",detail.getDiscount_percent());
            put("transaction_minimum",detail.getTransaction_minimum());
        }});
        }
        if ("EXCHANGE".equals(main.getStock_type())) {
            //换购卷
        object.put("exchange_coupon",new JSONObject(){{
            put("exchange_price",detail.getExchange_price());
            put("transaction_minimum",detail.getTransaction_minimum());
        }});
        }
        return object;
    }
}
